<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchList">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="搜索名称">
              <a-input v-model="queryParam.name" placeholder="" />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="适用方">
              <a-select v-model="queryParam.type" placeholder="请选择" default-value="null" :getPopupContainer="triggerNode => triggerNode.parentNode" @change="changeType">
                <a-select-option value="">全部</a-select-option>
                <a-select-option :value="2">集团</a-select-option>
                <a-select-option :value="1">BOX</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <template v-if="queryParam.type == 2">
            <a-col :md="8" :sm="24">
              <a-form-item label="适用品牌">
                <a-select v-model="queryParam.brandId" placeholder="请选择" default-value="null" :getPopupContainer="triggerNode => triggerNode.parentNode" @change="changeBrand">
                  <a-select-option value="">全部</a-select-option>
                  <a-select-option v-for="(item, index) in arcBrandsList" :key="index" :value="item.weid">{{ item.brandName }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="适用卡等级">
                <a-select v-model="queryParam.cardLevel" placeholder="请选择" default-value="null" :getPopupContainer="triggerNode => triggerNode.parentNode">
                  <a-select-option value="">全部</a-select-option>
                  <a-select-option v-for="(item, index) in cardList" :key="index" :value="item.id">{{ item.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </template>
          <a-col :md="8" :sm="24">
            <a-form-item label="状态">
              <a-select v-model="queryParam.status" placeholder="请选择" default-value="null" :getPopupContainer="triggerNode => triggerNode.parentNode">
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="0">禁用</a-select-option>
                <a-select-option value="1">启用</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <!-- <a-col :md="8" :sm="24">
            <a-form-item label="商品类型">
              <a-select
                v-model="queryParam.type"
                placeholder="请选择"
                default-value="null"
                :getPopupContainer="triggerNode => triggerNode.parentNode"
              >
                <a-select-option value="null">全部</a-select-option>
                <a-select-option value="2000">会员卡</a-select-option>
              </a-select>
            </a-form-item>
          </a-col> -->
          <a-col :md="queryParam.type == 2 ? 8 : 24" :sm="24">
            <span class="table-page-search-submitButtons" :style="{ float: 'right', overflow: 'hidden' }">
              <a-button type="primary" @click="searchList">查询</a-button>
              <a-button style="margin-left: 8px" @click="resetList">重置</a-button>
              <a-button style="margin-left: 8px" type="primary" icon="plus" @click="handleAdd">新建</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <s-table ref="table" size="default" :rowKey="columns.id" :columns="columns" :data="loadData" :pagination="paginationProps">
      <span slot="status" slot-scope="text">
        <a-badge :status="text | statusTypeFilter" :text="text | statusFilter" />
      </span>
      <!-- <span slot="type" slot-scope="text">{{ text | goodsType }}</span> -->
      <span slot="applicableParty" slot-scope="text">{{ text | ogType }}</span>
      <span slot="brandId" slot-scope="text, r">{{ brandFilter(text, r, arcBrandsList) }}</span>
      <span slot="cardLevel" slot-scope="text, r">{{ cardFilter(text, r, allCards) }}</span>
      <span slot="price" slot-scope="text">{{ text | goodsPrice }}</span>
      <span slot="createTime" slot-scope="text">{{ text | utc2beijing }}</span>
      <span slot="action" slot-scope="text, record">
        <template>
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a @click="handleEnable(record, 1)" v-show="record.status == 0">启用</a>
          <a @click="handleEnable(record, 0)" v-show="record.status == 1">禁用</a>

          <!-- <a-divider type="vertical" />
          <a @click="handleDetail(record)">查看</a> -->
        </template>
      </span>
    </s-table>
    <EditModal ref="editModal" @updateTable="updateTable"></EditModal>
  </a-card>
</template>
<script>
import { STable } from '../../components'
import { goodsCardList, updateStatus, brandCondition, cardTypeAllCondition, cardTypeCondition } from '@/api/box/product'
import { routeMixin } from '@/views/box/util/routeMixin'
import EditModal from './modules/editModal'

const columns = [
  { title: '权益包ID', width: 200, dataIndex: 'id', fixed: 'left', align: 'center' },
  { title: '权益包名称', width: 200, dataIndex: 'name', fixed: 'left', align: 'center' },
  // { title: '商品类型', dataIndex: 'type', align: 'center', scopedSlots: { customRender: 'type' } },
  { title: '适用方', dataIndex: 'applicableParty', align: 'center', scopedSlots: { customRender: 'applicableParty' } },
  { title: '适用品牌', dataIndex: 'brandId', align: 'center', scopedSlots: { customRender: 'brandId' } },
  { title: '适用卡等级', dataIndex: 'cardLevel', align: 'center', scopedSlots: { customRender: 'cardLevel' } },
  { title: '价格', dataIndex: 'price', align: 'center', scopedSlots: { customRender: 'price' } },
  { title: '状态', dataIndex: 'status', align: 'center', scopedSlots: { customRender: 'status' } },
  { title: '创建时间', dataIndex: 'createTime', align: 'center' },
  {
    title: '操作',
    key: 'operation',
    fixed: 'right',
    width: 150,
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]
const statusMap = {
  0: {
    status: 'error',
    text: '禁用'
  },
  1: {
    status: 'success',
    text: '启用'
  }
}
export default {
  mixins: [routeMixin],
  components: {
    STable,
    EditModal
  },
  data() {
    return {
      columns,
      // 查询条件参数
      queryParam: {
        name: '',
        type: '',
        status: ''
      },
      paginationProps: {
        total: 0,
        showTotal: total => `共有 ${total} 条数据`
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const queryParam = this.queryParam
        const data = {}
        data.page = parameter
        data.requestData = queryParam
        // const requestParameters = Object.assign({}, parameter, this.queryParam)

        return goodsCardList(data).then(res => {
          if (res.code === 0) {
            const data = res
            for (var i = 0; i < data.data.length; i++) {
              data.data[i].key = i
              data.data[i].price = data.data[i].goodsSkus[0].price
            }
            // console.log(data)
            return data
          } else {
            this.$message.error(res.msg)
            const data = {
              page: {
                pageNo: 1,
                pageSize: 10
              },
              data: []
            }
            return data
          }
        })
      },
      arcBrandsList: [],
      cardList: [],
      allCards: []
    }
  },
  computed: {
    brandFilter() {
      return (t, r, list) => {
        if (r.applicableParty == 2) {
          if (t && list) {
            let result = list.filter(e => e.weid == t)
            return result.length ? result[0].brandName : t
          }
          return t
        }
        return '-'
      }
    },
    cardFilter() {
      return (t, r, list) => {
        if (r.applicableParty == 2) {
          if (t && list) {
            let result = list.filter(e => e.id == t)
            return result.length ? result[0].name : t
          }
          return t
        }
        return '-'
      }
    }
  },
  filters: {
    statusFilter(type) {
      return statusMap[type].text
    },
    statusTypeFilter(type) {
      return statusMap[type].status
    },
    goodsType(type) {
      if (type === 2000) {
        return '会员卡'
      }
    },
    goodsPrice(price) {
      const yuan = price / 100
      return yuan
    },
    ogType(type) {
      if (type === 2) {
        return '集团'
      } else if (type === 1) {
        return 'BOX'
      } else {
        return type
      }
    }
  },
  watch: {
    $route(to, from) {
      if (this.siblingNameList.includes(from.name) && to.path == this.currentPath) {
        // console.log(this.queryParam)
        this.$refs.table.refresh()
      } else if (this.siblingNameList.includes(to.name) && from.path == this.currentPath) {
      } else {
        if (to.path == this.currentPath && !this.siblingNameList.includes(from.name)) {
          console.log('******* page-refresh-true *******')
          this.resetList()
        }
      }
    }
  },
  mounted() {
    this.fetchBrands()
    this.fetchAllCards()
  },
  methods: {
    // onSelectChange (selectedRowKeys, selectedRows) {
    //   this.selectedRowKeys = selectedRowKeys
    //   this.selectedRows = selectedRows
    // },
    handleAdd() {
      this.$refs.editModal.showModal('add')
      // this.$router.push('/box/product/fictitious/edit/add')
    },
    handleEdit(record) {
      // this.$router.push(`/box/product/fictitious/edit/${record.id}`)
      this.$refs.editModal.showModal(record.id)
    },
    handleDetail(record) {
      this.$router.push(`/box/product/fictitious/detail/${record.id}`)
    },
    handleEnable(record, type) {
      record.status = type
      const data = {
        requestData: {
          status: type,
          id: record.id
        }
      }
      updateStatus(data)
        .then(res => {
          if (res.code === 0) {
            this.$message.success(res.msg)
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log('submitCreate:' + err)
        })
    },
    searchList() {
      this.$refs.table.refresh(true)
    },
    resetList() {
      this.queryParam = {
        name: '',
        type: '',
        status: ''
      }
      this.$refs.table.refresh(true)
    },
    updateTable() {
      this.$refs.table.refresh()
    },
    fetchBrands() {
      brandCondition().then(res => {
        if (res.code == 0) {
          this.arcBrandsList = res.data
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    fetchAllCards() {
      cardTypeAllCondition().then(res => {
        if (res.code == 0) {
          this.allCards = res.data
        }
      })
    },
    changeType(v) {
      this.queryParam.brandId = ''
      this.queryParam.cardLevel = ''
      this.cardList = []
    },
    changeBrand(value) {
      this.cardList = []
      this.queryParam.cardLevel = ''
      if (value) this.fetchCardLevel(value)
    },
    fetchCardLevel(id) {
      let params = {
        weid: id
      }
      return cardTypeCondition(params).then(res => {
        if (res.code == 0) {
          this.cardList = res.data
        }
      })
    }
  }
}
</script>

